<template>
	<div class="exam-container bg-fff p20">
		<div class="exam-header bor-r-10 p30 mb20" v-if="isTop">
			<div class="header-title f20 f-bold txtc">{{ title }}</div>

			<div class="progress-container h20 mt20">
				<div class="progress-bar bg-grey" :style="{ width: progressWidth }"></div>
			</div>
		</div>

		<div class="exam-content bor-r-10 p30 mb20" v-if="topic.id">
			<div class="question-section">
				<div class="question-title f18 f-bold mb30">
					{{ topic.content }}
					<span class="question-type bg-grey f12 p5 bor-r-5 ml10">{{ getQuestionTypeText(topic.questionType) }}</span>
				</div>
				<div class="options-container">
					<div v-for="(op, i) in opArr" :key="i" @click="optionClick(i)" class="option-item p20 mb15 bor-r-5"
						:class="[op.selected ? 'option-selected' : 'bg-fff', op.clicked ? 'option-clicked' : '']">
						<div class="option-label f16">{{ op.value }}：{{ op.label }}</div>
					</div>
				</div>
			</div>

			<div class="action-buttons txtc mt40" v-if="isSub">
				<el-button class="submit-button bg-grey p10 pl30 pr30 f16" @click="subBtn()">{{ subText }}</el-button>
			</div>

			<div class="navigation-buttons txtc mt40" v-else>
				<el-button class="nav-button prev-button mr20 p10 pl20 pr20 f16" v-show="isPrev" @click="setNew(-1)">
					上一题
				</el-button>
				<el-button class="nav-button next-button bg-grey p10 pl20 pr20 f16" v-show="isNext" @click="setNew(1)">
					下一题
				</el-button>
			</div>
		</div>

	</div>
</template>

<script>
import { listTopic, listTopicForTask, getTopic, delTopic, addTopic, updateTopic ,saveUserAnswer } from "@/api/demo/topic/topic";

export default {
	props: {
		title: {
			type: String,
			required: true
		},
		data: {
			type: Array,
			required: true
		},
		returnUrl: {
			type: String,
			required: false
		},
		isTop: {
			type: Boolean,
			default: true
		},
		isStep: {
			type: Boolean,
			default: true
		},
		isBottom: {
			type: Boolean,
			default: true
		},
		subText: {
			type: String,
			default: '提交'
		}
	},
	watch: {
		title(newTitle) {
			console.log('标题更新为:', newTitle);
		},
		data(newData) {
			console.log('题目内容更新为:', newData);
		},
		isTop(newVal) {
			console.log('isTop 状态变为:', newVal);
		},
		isBottom(newVal) {
			console.log('isBottom 状态变为:', newVal);
		},
		returnUrl(newVal) {
			console.log('returnUrl 变为:', newVal);
		}
		
	},
	data() {
		return {
			nowTopic: 0,
			topic: {},
			opArr: [],
			isPrev: false,
			isNext: false,
			isSub: false,
			examStartTime: this.formatDate(new Date()) // 修改为格式化的时间

		}
	},
	computed: {
		progressWidth() {
			// 修改为基于单一题目列表的进度计算
			if (!this.data || !Array.isArray(this.data) || this.data.length === 0) {
				return '0%';
			}

			const totalTopics = this.data.length;
			const completedTopics = this.nowTopic;
			return totalTopics > 0 ? `${(completedTopics / totalTopics) * 100}%` : '0%';
		}
	},
	// 将uniapp的onShow替换为Vue的mounted
	mounted() { },
	created() {
		// 简化数据校验，移除分组相关逻辑
		if (!this.data || !Array.isArray(this.data) || this.data.length === 0) {
			console.error('Invalid data provided to exam component');
			return;
		}

		console.log(this.data);
		this.setTopic();
	},
	methods: {
		// 添加日期格式化方法
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		// 添加获取题目类型文字的方法
		getQuestionTypeText(questionType) {
			switch (questionType) {
				case 1: return '单选题';
				case 2: return '多选题';
				case 3: return '判断题';
				default: return '';
			}
		},
		optionClick(i) {
			// 添加数据校验
			if (!this.opArr || !Array.isArray(this.opArr)) {
				console.error('Invalid topic options data');
				return;
			}

			// 添加点击效果
			this.$set(this.opArr[i], "clicked", true);
			
			// 根据题目类型处理点击逻辑
			if (this.topic.questionType === 2) {
				// 多选题逻辑 - 如果已选中则取消选中，否则选中
				const isSelected = this.opArr[i].selected;
				this.$set(this.opArr[i], "selected", !isSelected);
				// 更新答案
				const selectedOptions = this.opArr.filter(item => item.selected);
				this.topic.userAnswer = selectedOptions.map(item => item.value).join(',');
				this.isNext = true;
			} else {
				// 单选题和判断题逻辑 - 取消其他选项的选中状态，选中当前选项
				const isSelected = this.opArr[i].selected;
				
				// 如果当前选项已选中，则取消选中
				if (isSelected) {
					this.$set(this.opArr[i], "selected", false);
					this.topic.userAnswer = '';
				} else {
					// 否则选中当前选项，取消其他选项的选中状态
					this.opArr.forEach((item, iio) => {
						if (iio == i) {
							this.$set(this.opArr[iio], "selected", true);
						} else {
							this.$set(this.opArr[iio], "selected", false);
						}
					});
					this.topic.userAnswer = this.opArr[i].value;
				}
			}
			this.topic.selected = this.opArr.some(op => op.selected);

			// 单选和判断题只有在有答案时才自动跳转到下一题
			if (this.topic.questionType !== 2 && this.topic.userAnswer) {
				setTimeout(() => {
					this.setNew(1);
				}, 500);
			}
		},
		setTopic() {
			// 简化题目设置逻辑，移除分组相关访问
			if (!this.data ||
				!Array.isArray(this.data) ||
				this.data.length === 0 ||
				this.nowTopic >= this.data.length) {
				console.error('Invalid data structure or indices');
				this.topic = {};
				return;
			}

			let d = this.data[this.nowTopic];
			// 确保 options 存在
			if (d) {
				this.opArr = Array.isArray(d.options) ? d.options : (typeof d.options === 'string' ? JSON.parse(d.options) : []);
				
				// 重置点击状态
				this.opArr.forEach(op => {
					op.clicked = false;
				});
				
				this.topic = d;
			} else {
				this.topic = {};
			}
			console.log("topic", this.topic)
		},
		setNew(i) {
			// 简化导航逻辑，移除分组相关逻辑
			if (!this.data || !Array.isArray(this.data) || this.data.length === 0) {
				console.error('Invalid data for navigation');
				return;
			}

			// 最后一题时显示提交按钮
			if (this.nowTopic == this.data.length - 1 && i > 0) {
				this.isSub = true;
				return;
			}
			// 第一题时不允许向前导航
			else if (this.nowTopic == 0 && i < 0) {
				return;
			}

			// 正常导航
			this.nowTopic = this.nowTopic + i;

			this.isPrev = this.nowTopic > 0;
			this.isNext = this.nowTopic < this.data.length - 1 && this.data[this.nowTopic].selected;
			this.setTopic();
		},
		subBtn() {
			// 答题提交接口

			// 获取开始考试时间（假设在组件创建时记录）
			const examDate = this.examStartTime ? this.examStartTime : this.formatDate(new Date());

			// 计算考试用时（假设在组件创建时记录开始时间）
			const timeSpent = this.examStartTime ?
				Math.floor((new Date().getTime() - new Date(this.examStartTime).getTime()) / 1000) :
				0;

			// console.log(this.data)

			let from = {
				examDate: examDate,
				timeSpent: timeSpent,
				taskTopicList: this.data,
				openId: localStorage.getItem('openID'),
			};

			// 将uniapp的API调用替换为标准的axios或fetch
			// 假设使用axios，并且this.$apis.saveUserAnswer已经适配为标准Promise
			saveUserAnswer(from).then(res => {
				if (res.code == 200) {
					// 显示分数，显示是否通过res.data.obtainedScore>=res.data.totalScore*0.8
					// 1秒后关闭所有页面，跳回this.returnUrl的路由
					const score = res.data.obtainedScore;
					const total = res.data.totalScore;
					const isPass = score >= total * 0.8;
					this.$emit("reExamClose",{taskTopicList:this.data,return:res.data})
					// // 将uni.showModal替换为标准的alert或自定义模态框
					// if (window.confirm(`考试结果\n考试完成，得分：${score}/${total}${isPass ? '，通过' : '，未通过'}`)) {
					// 	// 点击确认后跳转
					// 	if (this.returnUrl) {
					// 		// 将uni.redirectTo替换为Vue Router的replace
					// 		this.$router.replace(this.returnUrl);
					// 	} else {
					// 		// 将uni.navigateBack替换为Vue Router的go(-1)
					// 		this.$router.go(-1);
					// 	}
					// }
				} else {
					alert("提交失败");
				}
			}).catch(error => {
				alert("网络错误");
				console.error("提交答案失败:", error);
			});
		}
	}
}
</script>

<style scoped>
.exam-container {
	background-color: #f5f7fa;
}

.exam-header {
	background: linear-gradient(135deg, #6ea6fb, #7790e3);
	color: white;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.progress-container {
	height: 12rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 6rpx;
	overflow: hidden;
}

.progress-bar {
	height: 100%;
	background: #ffcc00;
	border-radius: 6rpx;
	transition: width 0.3s ease;
}

.exam-content {
	background: white;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.question-section {
	margin-bottom: 40rpx;
}

.question-title {
	color: #333;
	line-height: 1.5;
}

.option-item {
	border: 2rpx solid #e0e0e0;
	background: #fafafa;
	transition: all 0.3s ease;
	cursor: pointer;
}

.option-selected {
	border-color: #6e8efb;
	background: #6e8efb;
	color: white;
	box-shadow: 0 4rpx 10rpx rgba(110, 142, 251, 0.3);
}

.option-clicked {
	transform: scale(0.98);
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
	transition: all 0.2s ease;
}

.option-label {
	font-size: 30rpx;
}

.submit-button,
.nav-button {
	border: none;
	font-weight: bold;
	cursor: pointer;
	transition: all 0.3s ease;
}

.submit-button {
	background: linear-gradient(135deg, #6e8efb, #a777e3);
	color: white;
	box-shadow: 0 6rpx 15rpx rgba(110, 142, 251, 0.4);
}

.submit-button:active {
	transform: translateY(2rpx);
	box-shadow: 0 2rpx 10rpx rgba(110, 142, 251, 0.4);
}

.prev-button {
	background: white;
	color: #6e8efb;
	border: 2rpx solid #6e8efb;
}

.next-button {
	background: #6e8efb;
	color: white;
}
</style>